const express = require('express');
const router = express.Router();
const db = require('../db/index');
//管理员部分接口
//管理员登录
router.post('/a_login', (req, res) => {
    const a_id = req.body.user; // 将字符串转换为整数
    const a_pw = req.body.pw;
    console.log(req.body);
    console.log(a_id, a_pw);
    // 验证用户输入
    if (!a_id || !a_pw) {
        res.send({
            status: 0,
            msg: '请填写完整账号密码'
        });
        return;
    }
    // 设置数据库sql语句
    const sql = 'select * from a_login where a_id = ? and a_pw = ?';
    console.log("查询账户密码是否正确");
    db.query(sql, [a_id, a_pw], (err, result) => {
        console.log("查询账户密码是否正确");
        if (err) {
            res.send({
                status: 300,
                msg: '登录失败'
            });
            return;
        }
        if (result.length > 0) {
            res.send({
                status: 200,
                msg: '登录成功'
            });
        } else {
            res.send({
                status: 300,
                msg: '账号密码错误，请重试'
            });
        }
    });
});
function query(sql, values) {
    return new Promise((resolve, reject) => {
        db.query(sql, values, (err, result) => {
            if (err) {
                reject(err);
            } else {
                resolve(result);
            }
        });
    });
}
//管理员获取医生信息列表（o_order）
router.get('/a_orderList', (req, res) => {
        //使用连表查询，查询o_order表，并联接d_login表，都查询id再链上d_left,order的l_id等于d_left的l_id
        const sql = 'select * from o_order left join d_login on o_order.doctor_id = d_login.id left join d_left on o_order.l_id = d_left.l_id';
        db.query(sql, (err, result) => {
            if (err) {
                res.send({
                    status: 300,
                    msg: '预约信息获取失败'
                });
                console.log('报错');
                return;
            }if (result.length > 0) {
                console.log(result);
                res.send({
                    status: 200,
                    msg: '预约信息获取成功',
                    data: result
                })
            }else{
                res.send({
                    status: 300,
                    msg: '预约信息获取失败'
                });
            }
        });

});
//管理员删除医生信息(根据id，从o_order和d_login表都删掉传回来的id那条信息)
router.post('/delectDocter', (req, res) => {
    const id = req.body.id;
    const sql = 'delete from o_order where doctor_id = ?;';
    const sql1 = 'delete from d_login where id = ?';
    console.log(id);
    db.query(sql, [id, id, id], (err, result) => {
        if (err) {
            res.send({
                status: 300,
                msg: '删除失败'
            });
            console.log('报错');
            return;
        }
        if (result.affectedRows > 0) {
            db.query(sql1, [id], (err, result) => {
                if (err) {
                    res.send({
                        status: 300,
                        msg: '删除失败'
                    });
                    console.log('报错');
                    return;
                }
                if (result.affectedRows > 0) {
                   res.send({
                       status: 200,
                       msg: '删除成功'
                   })
                }else{
                    res.send({
                        status: 300,
                        msg: '删除失败'
                    });
                }
            })
        }
    })
});

//医生注册
router.post('/d_register', (req, res) => {
    console.log(req.body);
    const userForm = req.body;
    console.log(userForm);

    // 第一个插入语句
    const sql1 = 'insert into d_login set id=?, d_pw=?, name=?, post=?, office_id=?';
    const values1 = [userForm.id, userForm.d_pw, userForm.name, userForm.post, userForm.l_id];

    // 第二个插入语句
    const sql2 = 'insert into o_order set l_id=?, doctor_id=?, price=?, d_c=?';
    const values2 = [userForm.l_id, userForm.id, userForm.price, userForm.post];

    // 执行第一个插入语句
    db.query(sql1, values1, (err, result1) => {
        if (err) {
            console.log(err);
            res.send({
                status: 300,
                msg: '注册失败'
            });
            console.log('报错');
            return;
        }

        // 执行第二个插入语句
        db.query(sql2, values2, (err, result2) => {
            if (err) {
                console.log(err);
                res.send({
                    status: 300,
                    msg: '注册失败'
                });
                console.log('报错');
                return;
            }

            res.send({
                status: 200,
                msg: '注册成功'
            });
            console.log('成功');
        });
    });
});
//a_save管理员密码重置
router.post('/a_save', (req, res) => {
    const a_id = req.body.a_id;
    const a_pw = req.body.a_pw;
    const sql = 'update a_login set a_pw = ? where a_id = ?';
    db.query(sql, [a_pw, a_id], (err, result) => {
        if (err) {
            res.send({
                status: 300,
                msg: '重置失败'
            });
            console.log('报错');
            return;
        }if (result.affectedRows > 0) {
            res.send({
                status: 200,
                msg: '重置成功'
            });
        }else{
            res.send({
                status: 300,
                msg: '重置失败'
            });
        }
    });
});






//用户部分接口
// 用户登录
router.post('/u_login', (req, res) => {
    const num = req.body.user; // 将字符串转换为整数
    const pw = req.body.pw;
    console.log(req.body);
    if (!num || !pw) {
        res.send({
            status: 0,
            msg: '请填写完整账号密码'
        });
        return;
    }
    const sql = 'select * from u_login where num = ? and pw = ?';
    db.query(sql, [num, pw], (err, result) => {
        console.log("用户登录，查询账户密码是否正确");
        if (err) {
            res.send({
                status: 300,
                msg: '登录失败'
            });
            console.log('报错');
            return;
        }
        if (result.length > 0) {
            res.send({
                status: 200,
                msg: '登录成功'
            });
            console.log('成功');
        } else {
            res.send({
                status: 300,
                msg: '账号密码错误，请重试'
            });
            console.log('失败');
        }
    });
});
//用户注册
router.post('/u_register', (req, res) => {
    const userForm = req.body;
    console.log(userForm);
    if (!userForm.name || !userForm.user || !userForm.pw || !userForm.sex) {
        res.send({
            status: 0,
            msg: '请填写完整信息'
        });
        return;
    }
    //查询手机号是否被注册
    const sql_phone = 'select * from u_login where num = ?';
    db.query(sql_phone, [userForm.user], (err, result) => {
        if (err) {
            res.send({
                status: 300,
                msg: '注册失败'
            });
            console.log('报错');
            return;
        }if(result.length > 0) {
            res.send({
                status: 300,
                msg: '手机号已被注册'
            });
            //不再执行后续sql语句
            return;
        }else{
            console.log('更新数据');
            const userdata = {
                num: userForm.user,
                pw: userForm.pw,
                name: userForm.name,
                sex: userForm.sex,
            };
            const sql = 'insert into u_login set num=?,pw=?,name=?,sex=?';
            db.query(sql, [userdata.num,userdata.pw,userdata.name,userdata.sex], (err, result) => {
                if (err) {
                    res.send({
                        status: 300,
                        msg: '注册失败'
                    });
                    console.log('报错');
                    return;
                }
                if (result.affectedRows != 0) {
                    res.send({
                        status: 200,
                        msg: '注册成功'
                    });
                }else{
                    res.send({
                        status: 300,
                        msg: '注册失败'
                    });
                }
            });
        }
    });
});
//预约左侧导航栏接口get方式
router.get('/u_leftList', (req, res) => {
    const sql = 'select * from d_left';
    db.query(sql, (err, result) => {
        if (err) {
            res.send({
                status: 300,
                msg: '预约信息获取失败'
            });
            console.log('报错');
            return;
        }
        if (result.length > 0) {
            console.log(result);
            res.send({
                status: 200,
                msg: '预约信息获取成功',
               data: result
            })
        }
    })
});
//预约获取部门的医生列表
router.get('/u_doctorList', (req, res) => {
    console.log(req.query);
    const l_id = req.query.l_id;
    //查询d_login表的office_id=l_id,然后连接d_order表，d_login.id = o_order.doctor_id,
    const sql = 'select * from d_login left join o_order on d_login.id = o_order.doctor_id where d_login.office_id = ?';
    db.query(sql, [l_id], (err, result) => {
        if (err) {
            res.send({
                status: 300,
                msg: '预约信息获取失败'
            });
            console.log('报错');
            return;
        }
        if (result.length > 0) {
            console.log(result);
            res.send({
                status: 200,
                msg: '医生列表获取成功',
                data: result
            })
        }else{
            res.send({
                status: 300,
                msg: '该类医生列表为空'
            })
        }
    });

});
//预约按钮
router.post('/u_appointment', (req, res) => {
    console.log(req.body);
    const sql_userInfo= 'select * from u_login where num = ?';
    console.log(req.body.user);
    db.query(sql_userInfo, [req.body.user], (err, result) => {
        if (err) {
            res.send({
                status: 300,
                msg: '预约失败'
            });
            console.log('报错');
            return;
        }if(result.length > 0) {
            console.log(result)
            const sql_doctorInfo = 'select * from d_login where office_id = ?';
            db.query(sql_doctorInfo, [req.body.d_id], (err, result1) => {
                if (err) {
                    res.send({
                        status: 300,
                        msg: '预约失败'
                    });
                    console.log('报错');
                    return;
                }if(result1.length >0) {
                    console.log(result1)
                    const o_time ={
                        t_num: result[0].num,
                        t_name: result[0].name,
                        t_id: result1[0].id,
                        t_time: req.body.date,
                        t_order: '否',
                        t_clinic: '否',
                        t_docter: result1[0].name,
                    }
                    console.log(o_time);
                    const sql='insert into o_time set t_num=?,t_name=?,t_id=?,t_time=?,t_order=?,t_clinic=?,t_docter=?'
                    db.query(sql, [o_time.t_num,o_time.t_name,o_time.t_id,o_time.t_time,o_time.t_order,o_time.t_clinic,o_time.t_docter], (err, result) => {
                        if (err) {
                            res.send({
                                status: 300,
                                msg: '预约失败'
                            });
                            console.log('报错',err);
                            return;
                        }if(result.affectedRows != 0) {
                            res.send({
                                status: 200,
                                msg: '预约成功'
                            });
                        }else{
                            res.send({
                                status: 300,
                                msg: '预约失败'
                            });
                        }
                    });
                }
            })
        }
    });

});
//获取自己的预约记录
// 获取自己的预约记录
router.post('/u_appointmentList', (req, res) => {

    const u_num = req.body.user;
    console.log(u_num);
    const sql = 'select * from o_time where t_num = ?';
    db.query(sql, [u_num], (err, result) => {
        if (err) {
            res.send({
                status: 300,
                msg: '预约信息获取失败'
            });
            return;
        }
        if (result.length > 0) {
            console.log(result);
            for (let i = 0; i < result.length; i++) {
                const date = new Date(result[i].t_time);
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0'); // 确保月份是两位数
                const day = String(date.getDate()).padStart(2, '0'); // 确保日期是两位数
                const formattedDate = `${year}-${month}-${day}`;
                result[i].t_time = formattedDate;
            }
            res.send({
                status: 200,
                msg: '预约信息获取成功',
                data: result
            });
        } else {
            res.send({
                status: 300,
                msg: '该用户没有预约记录'
            });
        }
    });
});
//取消预约
router.post('/u_cancel', (req, res) => {
    console.log(req.body.id);
    const sql = 'delete from o_time where id=?';
    db.query(sql, [req.body.id], (err, result) => {
        if (err) {
            res.send({
                status: 300,
                msg: '取消预约失败'
            });
            console.log('报错');
            return;
        }if(result.affectedRows != 0) {
            res.send({
                status: 200,
                msg: '取消预约成功'
            });
        }else{
            res.send({
                status: 300,
                msg: '取消预约失败'
            });
        }
    });
});
//根据用户id获取用户信息
router.post('/u_userInfo', (req, res) => {
    console.log(req.body.user);
    const sql = 'select * from u_login where num = ?';
    db.query(sql, [req.body.user], (err, result) => {
        if (err) {
            res.send({
                status: 300,
                msg: '获取用户信息失败'
            });
            console.log('报错');
        }if(result.length > 0) {
            console.log(result);
            res.send({
                status: 200,
                msg: '用户信息获取成功',
                data: result
            });
        }else{
            res.send({
                status: 300,
                msg: '获取用户信息失败，请重新登陆'
            });
        }
    })
})
//保存新的个人信息
router.post('/u_saveNewInfo', (req, res) => {
    console.log(req.body);
    const sql = 'update u_login set name=?,sex=?,pw=? where id=?'
    if(!req.body.newPw){

    }else{
        req.body.pw=req.body.newPw;
    }if(!req.body.newName){

    }else{
        req.body.name=req.body.newName;
    }if(!req.body.newSex){
        req.body.sex=req.body.newSex;
    }
    db.query(sql, [req.body.name, req.body.sex, req.body.pw, req.body.id], (err, result) => {
        if (err) {
            res.send({
                status: 300,
                msg: '保存失败'
            });
            console.log('报错');
            return;
        }if(result.affectedRows != 0) {
            res.send({
                status: 200,
                msg: '保存成功'
            });
        }else{
            res.send({
                status: 300,
                msg: '保存失败'
            });

        }
    });
});
//已到诊
router.post('/markAsArrived', (req, res) => {
    console.log(req.body.id);
    const t_order = '是';
    const sql = 'update o_time set t_order=? where id=?'
    db.query(sql, [t_order, req.body.id], (err, result) => {
        if (err) {
            res.send({
                status: 300,
                msg: '系统出错，请重新点击到诊'
            });
            console.log('报错');
            return;
        }if(result.affectedRows != 0) {
            res.send({
                status: 200,
                msg: '已到诊成功'
            });
        }else{
            res.send({
                status: 300,
                msg: '系统出错，请重新点击到诊'
            });
        }
    });
})






//医生部分
//医生登录
router.post('/d_login', (req, res) => {
    const id = req.body.user;
    const d_pw = req.body.pw;
    console.log(req.body);
    if (!id || !d_pw) {
        res.send({
            status: 0,
            msg: '请填写完整账号密码'
        });
        return;
    }
    const sql = 'select * from d_login where id = ? and d_pw = ?';
    db.query(sql, [id, d_pw], (err, result) => {
        console.log("医生登录，查询账户密码是否正确");
        if (err) {
            res.send({
                status: 300,
                msg: '登录失败'
            });
            console.log('报错');
            return;
        }
        if (result.length > 0) {
            res.send({
                status: 200,
                msg: '登录成功'
            });
            console.log('成功');
        } else {
            res.send({
                status: 300,
                msg: '账号密码错误，请重试'
            });
            console.log('失败');
        }
    });
});
//d_info根据id获取医生信息d_login
router.post('/d_info', (req, res) => {
    console.log(req.body);
    const sql = 'select * from d_login where id = ?';
    db.query(sql, [req.body.id], (err, result) => {
        if (err) {
            res.send({
                status: 300,
                msg: '获取医生信息失败'
            });
            console.log('报错');
        }if(result.length > 0) {
            res.send({
                status: 200,
                msg: '获取医生信息成功',
                data: result
            });
        }else{
            res.send({
                status: 300,
                msg: '获取医生信息失败，请重新登陆'
            });

        }
    })
})
//d_save保存医生密码
router.post('/d_save', (req, res) => {
    console.log(req.body);
    const sql = 'update d_login set d_pw=? where id=?'
    db.query(sql, [req.body.pw, req.body.id], (err, result) => {
        if (err) {
            res.send({
                status: 300,
                msg: '保存失败'
            });
            console.log('报错');
            return;
        }if(result.affectedRows != 0) {
            res.send({
                status: 200,
                msg: '保存成功'
            });
        }else{
            res.send({
                status: 300,
            })
        }
    });

});
//d_time获取今日医生预约信息
router.post('/d_time', (req, res) => {
    console.log(req.body);
    //获取今日日期
    const date = new Date();
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const dateStr = year + '-' + month + '-' + day;
    console.log(dateStr);
    const sql = 'select * from o_time where t_id = ? and t_time = ?';
    db.query(sql, [req.body.id, dateStr], (err, result) => {
        if (err) {
            res.send({
                status: 300,
                msg: '获取预约信息失败'
            });
            console.log('报错');
        }if(result.length > 0) {
            console.log(result);
            //格式化每一个时间段为yyyy-mm-dd
            for (let i = 0; i < result.length; i++) {
                const date = new Date(result[i].t_time);
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0'); // 确保月份是两位数
                const day = String(date.getDate()).padStart(2, '0'); // 确保日期是两位数
                const formattedDate = `${year}-${month}-${day}`;
                result[i].t_time = formattedDate;
            }
            res.send({
                status: 200,
                msg: '获取预约信息成功',
                data: result
            });
        }else{
            res.send({
                status: 300,
                msg: '今日没有预约信息'
            })
        }
    })
})
router.post('/reservation', (req, res) => {
    console.log(req.body);
    const sql = 'update o_time set t_clinic=? where id=?'
    db.query(sql, [req.body.t_clinic, req.body.id], (err, result) => {
        if (err) {
            res.send({
                status: 300,
                msg: '预约接诊失败'
            });
            console.log('报错');
            return;
        }if(result.affectedRows != 0) {
            res.send({
                status: 200,
                msg: '预约接诊成功'
            });
        }else{
            res.send({
                status: 300,
                msg: '预约接诊失败，请重新预约接诊'
            })
        }
    });
})


module.exports = router;